package com.example.yunhailutong.zhongtan.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;


import com.example.yunhailutong.zhongtan.app.App;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.os.Environment.MEDIA_MOUNTED;

/**
 * @author gordon
 * @date 2015年10月13日 下午10:25:52
 */
public class Utils {
    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

    //转译字符
    public static String unescapeUnicode(String str) {
        StringBuffer b = new StringBuffer();
        Matcher m = Pattern.compile("\\\\u([0-9a-fA-F]{4})").matcher(str);
        while (m.find())
            b.append((char) Integer.parseInt(m.group(1), 16));
        return b.toString();
    }

    /**
     * @param sA  是第一个字符(大的字符串)
     * @param sB  被包含的字符串
     * @param num sB在sA 中第几次出现  num 必须大于1
     * @return sB 在sA 中第num次出现的位置
     * @author wyd 2012-12-17
     * 一个字符串在另一个字符串中 第N次出现的位置
     * (如果是倒序则将indexOf改成lastIndexOf)
     * 使用 :
     * int num = getStringNum("aaasdfzsssasef", "s", 10);
     * System.out.println(num);
     */
    public static int getStringNum(String sA, String sB, int num) {
        int weizhi = 0;
        for (int i = 1; i < num; i++) {
            if (weizhi == 0) {
                weizhi = sA.toString().indexOf(sB);
            }
            weizhi = sA.indexOf(sB, weizhi + 1);
        }
        return weizhi + 1;
    }

    private final static ThreadLocal<StringBuilder> threadSafeStrBuilder = new ThreadLocal<StringBuilder>();

    public static <T> boolean isEmpty(List<T> list) {
        if (list == null || list.size() == 0) {
            return true;
        }
        return false;
    }

    public static <T> boolean isEmpty(T[] ary) {
        if (ary == null || ary.length == 0) {
            return true;
        }
        return false;
    }

    /**
     * 检测sd卡是否已经挂载
     */
    public static boolean isSDCardMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 创建sdcard0/yemclient根目录
     */
    public static void createRootDirOnSdcard0() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 创建一个文件夹对象，赋值为外部存储器的目录
            File sdcardDir = Environment.getExternalStorageDirectory();
            // 得到一个路径，内容是sdcard的文件夹路径和名字
            String path = sdcardDir.getPath() + "/yemclient";
            File rootPath = new File(path);
            if (!rootPath.exists()) {
                // 若不存在，创建目录，可以在应用启动的时候创建
                rootPath.mkdirs();
            }
        }
    }

    public static void createDirOnSdcard0(String filepath) {
//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            // 创建一个文件夹对象，赋值为外部存储器的目录
//            File sdcardDir = Environment.getExternalStorageDirectory();
//            // 得到一个路径，内容是sdcard的文件夹路径和名字
//            String path = sdcardDir.getPath() + filepath;
        File rootPath = new File(filepath);
        if (!rootPath.exists()) {
            // 若不存在，创建目录，可以在应用启动的时候创建
            rootPath.mkdirs();
        }
//        }
    }

    //判断是否是手机号
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isCarNo(String carNo) {
        Pattern p = Pattern.compile("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(?:(?![A-Z]{4})[A-Z0-9]){4}[A-Z0-9挂学警港澳]{1}$");
        Matcher m = p.matcher(carNo);
        if (!m.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 获取App的根目录
     *
     * @return
     */
    public static String getRootDir() {
        String rootRoot = Environment.getExternalStorageDirectory().toString() + "/yemclient";
        return rootRoot;
    }

    public static String getRoot_PhotoDir() {
        String photoDir = getRootDir() + "/photo";
        return photoDir;
    }

    /**
     * 判断网络是否可用
     *
     * @param ctx
     * @return
     */
    public static boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean available = false;
        NetworkInfo networkInfo = mgr.getActiveNetworkInfo();
        if (networkInfo != null) {
            available = networkInfo.isAvailable() || networkInfo.isConnectedOrConnecting();
        }
        return available;
    }

    /**
     * 获取线程安全的StringBuilder
     */
    public static StringBuilder getThreadSafeStringBuilder() {
        StringBuilder sb = threadSafeStrBuilder.get();

        if (sb == null) {
            sb = new StringBuilder();
            threadSafeStrBuilder.set(sb);
        }

        sb.delete(0, sb.length());
        return sb;
    }

    /**
     * 获取设备IMEI码
     *
     * @param context
     * @return
     */
    public static String getImei(Context context) {
        String imei = "";
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            Log.e(Utils.class.getSimpleName(), e.getMessage());
        }
        return imei;
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static String GetVersion(Context context) {
        try {
            PackageInfo manager = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return manager.versionName;
        } catch (NameNotFoundException e) {
            return "Unknown";
        }
    }

    /**
     * MD5加密算法
     *
     * @param
     * @return
     */
    public static String md5(String value) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(value.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 写入磁盘
     *
     * @param bitmap
     */
    public static void write2disk(Bitmap bitmap) throws IOException {
        FileOutputStream outputStream = null;
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            cachePath = App.context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
            String path = Environment.getExternalStorageDirectory().getPath();
            System.out.println(path);
        } else {
            cachePath = App.context.getCacheDir().getPath();
        }
        File file = new File(cachePath + File.separator + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".png");
        file.createNewFile();
        if (file.exists()) {
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 95, outputStream);
            outputStream.flush();
        }
        if (outputStream != null)
            outputStream.close();
        App.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + cachePath)));
    }


    public static void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(App.context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        App.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + appDir.getPath())));
    }

    //检测电话号码是否符合规则
    public static boolean telCheck(String tel) {
        Pattern p = Pattern.compile("^((13\\d{9}$)|(15[0,1,2,3,5,6,7,8,9]\\d{8}$)|(18[0,2,5,6,7,8,9]\\d{8}$)|(147\\d{8})$)");
        Matcher m = p.matcher(tel);
        return m.matches();
    }

    /**
     * Returns application cache directory. Cache directory will be created on SD card
     * <i>("/Android/data/[app_package_name]/cache")</i> if card is mounted and app has appropriate permission. Else -
     * Android defines cache directory on device's file system.
     *
     * @param context Application context
     * @return Cache {@link File directory}
     */
    public static File getCacheDirectory(Context context) {
        File appCacheDir = null;
        if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
            Log.w("fileUtils", "Can't define system cache directory! The app should be re-installed.");
        }
        return appCacheDir;
    }


    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
        if (!appCacheDir.exists()) {
            if (!appCacheDir.mkdirs()) {
                Log.w("fileUtils", "Unable to create external cache directory");
                return null;
            }
            try {
                new File(appCacheDir, ".nomedia").createNewFile();
            } catch (IOException e) {
                Log.i("fileUtils", "Can't create \".nomedia\" file in application external cache directory");
            }
        }
        return appCacheDir;
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    public static String dateFormat_day = "HH:mm";
    public static String dateFormat_month = "MM-dd";

    /**
     * 时间转换成字符串,默认为"yyyy-MM-dd HH:mm:ss"
     *
     * @param time 时间
     */
    public static String dateToString(long time) {
        return dateToString(time, "yyyy-MM-dd");
    }

    /**
     * 时间转换成字符串,指定格式
     *
     * @param time   时间
     * @param format 时间格式
     */
    public static String dateToString(long time, String format) {
        Date date = new Date(time);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }


    public static String getDays(int days) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        date = calendar.getTime();
        String time = dateToString(date.getTime());
        return time;

    }

    public static File getFileByUri(Uri uri, Activity activity) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = activity.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        } else {
            Log.i("images", "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

}
